//
//  MaterialAcceptMaterialController.m
//  ERP
//
//  Created by QA on 2016/10/10.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MaterialAcceptMaterialController.h"

#import "UITableView+Custom.h"
#import "MJRefresh.h"
#import "MaterialAcceptMaterialCell.h"
#import "MaterialAcceptMaterialRowCell.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "WebServiceCommonRequest.h"
#import "GEDateFromatter.h"

#import "MaterialAcceptListController.h"

@interface MaterialAcceptMaterialController ()<SKSTableViewDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;

@end

@implementation MaterialAcceptMaterialController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"验收材料类型"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.SKSTableViewDelegate = self;
    self.tableView.shouldExpandOnlyOneCell = YES;
    //self.tableView.subRowBackgroundColor = [UIColor colorWithWhite:0.97 alpha:1];
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self setupRefresh];
}

- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];

}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self getNetWorkData];
}

#pragma mark 网络获取数据

- (void)getNetWorkData
{
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCYS_GLGYS_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:[model.stationId integerValue]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        
        //添加数据，刷新页面
        [self.resultData removeAllObjects];
        if(result.resultArray && result.resultArray.count>1){
            NSMutableArray *valueArray = [self dataQueryHandle:result.resultArray];
            [self.resultData addObjectsFromArray:valueArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView refreshData];
            
            if(!(valueArray && valueArray.count > 0))
                [self.tableView setTableViewNotDataDrawText:@"暂无原材数据" isShow:YES];
            
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无原材数据" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (NSMutableArray*)dataQueryHandle:(NSArray*)array
{
    //数据查询
    NSMutableArray *compArray = [NSMutableArray arrayWithArray:[array firstObject]];
    NSMutableArray *htArray = [NSMutableArray arrayWithArray:[array lastObject]];
    
    for(int i=0;i<compArray.count;i++){
        NSDictionary *dic = [compArray objectAtIndex:i];
        
        NSArray *filteredArray = nil;
        NSInteger clientID = [dic objectFormatIntegerForKey:@"CLID"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CLID==%ld", clientID];
        filteredArray = [htArray filteredArrayUsingPredicate:predicate];
        
        NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [mutableDic setValue:filteredArray forKey:@"itemValue"];
        [compArray setObject:mutableDic atIndexedSubscript:i];
    }
    
    return compArray;
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    return rowValueArray.count <= 0 ? 0 : rowValueArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MaterialAcceptMaterialCell";
    MaterialAcceptMaterialCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell){
        cell = [[MaterialAcceptMaterialCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell setIsShowAccessory:YES];
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
    cell.nameLabel.text = [itemData objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MCChargeInRowViewCell";
    MaterialAcceptMaterialRowCell *cell = [[MaterialAcceptMaterialRowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    
    NSDictionary *itemData = [rowValueArray objectAtIndex:indexPath.subRow - 1];
    cell.nameLabel.text = [itemData objectFormatStringForKey:@"供应商" defaults:@"未知"];
    
    return cell;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    if (rowValueArray.count <= 0) return 44;
    else return 44;
}

#pragma mark -
#pragma mark SKSTableViewDelegate

- (void)tableView:(SKSTableView *)tableView accessoryDidExpandIndexPath:(NSIndexPath *)indexPath
{
//    NSIndexPath *indexRowPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
//    MaterialAcceptMaterialRowCell *cell = [tableView cellForRowAtIndexPath:indexRowPath];
//    if(cell && [cell isKindOfClass:[MaterialAcceptMaterialRowCell class]])[cell setChartViewAnimated];
}

- (void)tableView:(SKSTableView *)tableView accessoryNotExpandIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", (long)indexPath.section, indexPath.row, (long)indexPath.subRow);
}

- (void)tableView:(SKSTableView *)tableView didSelectSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", indexPath.section, (long)indexPath.row, (long)indexPath.subRow);
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    NSDictionary *itemData = [rowValueArray objectAtIndex:indexPath.subRow-1];
    
    MaterialAcceptListController *mOrderDetails = [[MaterialAcceptListController alloc] initWithValue:itemData];
    [self.navigationController pushViewController:mOrderDetails animated:YES];
    
}

@end

